package tge

import (
)

type WebSocketServer interface {
	SetCreateAgent(func(Conn) Agent)
	StartServer(string)
	Close()
}

// 网关模块，提供网关功能

type Gate struct {
	TcpPort	string
	UdpPort	string
	WsPort string
	CreateParser func()ProtoParser 	// 协议解析器创建方法，用于新建解析器
	Route 	Route 			// 消息路由器
	OnNewAgent func(Agent) 	// 当有新的连接代理被创建时调用

	WsServer WebSocketServer 	// web socket 服务

	PacketLen int		// 数据包的长度，默认是 2

	createAgentFunc 	func(Conn) Agent
}

func (g *Gate) Init() {
	if 0 == g.PacketLen {
		g.PacketLen = 2
	}
	g.createAgentFunc = func(conn Conn) Agent {
		a := NewAgenter(g.CreateParser(), g.Route, conn)
		if nil != g.OnNewAgent {
			g.OnNewAgent(a)
		}
		return a
	}
}

func (g *Gate) Run(closeSig chan bool) {
	var tcpServer *Server
	if g.TcpPort != "" { 	// 启动 tcp 服务器
		tcpServer = NewServer()
		tcpServer.Parser.SetPacketLenByte(g.PacketLen)
		tcpServer.CreateAgent = g.createAgentFunc
		go tcpServer.StartServer(g.TcpPort)
	}
	var udpServer *UdpServer
	if g.UdpPort != "" { 	// 启动 udp 服务器
		udpServer = NewUdpServer()
		udpServer.Parser.SetPacketLenByte(g.PacketLen)
		udpServer.CreateAgent = g.createAgentFunc
		go udpServer.StartServer(g.UdpPort)
	}
	if g.WsPort != "" && nil != g.WsServer {
		g.WsServer.SetCreateAgent(g.createAgentFunc)
		go g.WsServer.StartServer(g.WsPort)
	}

	<-closeSig
	if nil != tcpServer {
		tcpServer.Close()
		tcpServer = nil
	}
	if nil != udpServer {
		udpServer.Close()
		udpServer = nil
	}

	if nil != g.WsServer {
		g.WsServer.Close()
	}
}

func (g *Gate) Destroy() {
	logger.Println("Destroy Mod Gate")
}